package Orm.jdbc.jdbcMetadata;

import Orm.jdbc.connectorPool.JDBCUtils;

import java.sql.*;
import java.util.*;

/**
 * 通过ResultSetMetaData对象，我们可以获取表的列的类型信息
 * 这对于构造ORM框架进行自填充起到了很大的作用
 */
public class ResultSetMetaDataStudy {

    public static void main(String[] args) throws SQLException {
        //获取连接
        Connection conn = JDBCUtils.getConnection();
        //定义sql
        String sql = "select * from city";
        //预编译
        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();

        // 获得结果集元数据
        ResultSetMetaData resultSetMetaData = rs.getMetaData();

        int count = resultSetMetaData.getColumnCount();
        List<String> columnNameList = new ArrayList<>();
        Map<String,String> columnTypeMap = new HashMap<>();
        // 打印table 第一行
        for (int i = 1; i <= count; i++) {
            String columnName = resultSetMetaData.getColumnName(i);
            //System.out.print( columnName+ "\t");
            columnNameList.add(columnName);
        }
        System.out.println();

        // 打印每列类型
        for (int i = 1; i <= count; i++) {
            String type = resultSetMetaData.getColumnTypeName(i);
            //System.out.print( type+ "\t");
            columnTypeMap.put(columnNameList.get(i-1),type);
        }
        System.out.println();
        System.out.println(columnTypeMap);

    }
}
